﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace BestEasy.Core.Extensions
{
    /// <summary>
    /// [扩展] 字符串
    /// </summary>
    public static class StringExtensions
    {
        /// <summary>
        /// 验证IP地址
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public static bool IsIp(this string ip)
        {
            //return Regex.IsMatch(ip, @"^(d{1,2}|1dd|2[0-4]d|25[0-5]).(d{1,2}|1dd|2[0-4]d|25[0-5]).(d{1,2}|1dd|2[0-4]d|25[0-5]).(d{1,2}|1dd|2[0-4]d|25[0-5])$");
            return Regex.IsMatch(ip, @"^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$");
        }
        /// <summary>
        /// 验证电子邮箱
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        public static bool IsEmail(this string email)
        {
            return Regex.IsMatch(email, @"^([/w-/.]+)@((/[[0-9]{1,3}/.[0-9] {1,3}/.[0-9]{1,3}/.)|(([/w-]+/.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(/)?]$");
        }
        /// <summary>
        /// 验证URL
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static bool IsUrl(this string url)
        {
            return Regex.IsMatch(url, @"http(s)?://([/w-]+/.)+[/w-]+(/[/w- ./?%&=]*)?");
        }

        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="strValue">要加密的字符串</param>
        /// <returns>加密后的字符串</returns>
        public static string ToMd5Encrypt(this string strValue)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            var fromData = Encoding.Unicode.GetBytes(strValue);
            var targetData = md5.ComputeHash(fromData);

            return targetData.Aggregate<byte, string>(null, (current, t) => current + t.ToString("x")).ToUpper();
        }
    }
}
